import { defineStore } from "pinia";
import { ref, onMounted, onBeforeUnmount, reactive,toRefs } from "vue";


export const useTimeStore = defineStore('time', () => {
  const state = reactive({
    currentDate: '',
    currentTime: ''
  })
  let timer = null

  // 2022.01.01 18:00
  function updateTime() {
    const date = new Date()
    state.currentDate = date.toISOString().split('T')[0]
    state.currentTime = date.toTimeString().substring(0, 5)
  }

  const apiTime = reactive({
    currentDate: '',
    currentTime: ''
  })
  // 首页是接口的时间
  function updateTimeByApi(date) {
    apiTime.currentDate = date.split(' ')[0]
    apiTime.currentTime = date.split(' ')[1]
  }

  onMounted(() => {
    updateTime()
    timer = setInterval(() => {
      updateTime()
    }, 1000)
  })

  onBeforeUnmount(() => {
    clearInterval(timer)
  })
  return { 
    state,
    apiTime,
    ...toRefs(state), // 自动转换为 ref
    updateTimeByApi,
  }
})